package main.java.cn.wolfcode.web.controller;


import cn.wolfcode.domain.Activity;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IActivityItemService;
import cn.wolfcode.service.IActivityService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActivityItemService activityItemService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Activity> pageInfo = activityService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "activity/list";
    }




    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("activity",activityService.get(id));
            model.addAttribute("Items",activityItemService.selectByActivityId(id));
        }
        return "activity/input";
    }


    @RequestMapping("/result")
    public String result(Long optionsRadios,Long id,Model model) {
        Activity activity = activityService.get(id);
        model.addAttribute("activity",activity);
        model.addAttribute("Items",activityItemService.selectByActivityId(activity.getId()));
        //查询总条数
        model.addAttribute("sum",activityItemService.selectCount(activity.getId()));
        //投票对应所投的选项加一
        activityItemService.updateNumByActivityItemId(optionsRadios);
        return "activity/result";
    }

    @ResponseBody
    @RequestMapping(value = "/isVote",method = RequestMethod.POST)
    public JsonResult result(Long id) {
        //根据当前员工的id和所投票的活动主题的id查询中间表如果存在那么就为投过票的,否则就没有投票
        List<Long> longList = activityService.selectRelation(UserContext.getCurrentUser().getId(), id);
        if(!longList.isEmpty()){
             throw new RuntimeException("你已经投过票了,不能再投");
         }
         //存入当前投票的员工
        activityItemService.insertRelation(UserContext.getCurrentUser().getId(),id,
                new Date());

        return new JsonResult(true,"投票成功");
    }




}
